﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.SECURITY.BLL;
using KPIS.GERP.SECURITY.MODEL;
using KPIS.GERP.ESS.BLL;

namespace KPIS.GERP.GHRMS.APP
{
    public partial class Master : System.Web.UI.MasterPage
    {
        private UserBLL userBLL = new UserBLL();
        private UserRoleBLL uroleBLL = new UserRoleBLL();
	    private B_MessageSend send;//= new  B_MessageSend();
        private SysMenuItemListBLL bll = new SysMenuItemListBLL();
        private SsMng ssMng = new SsMng();
        public static string strServerName;

        protected void Page_Load(object sender, EventArgs e)
        {
            strServerName = Request.Url.Host + (ConfigurationSettings.AppSettings["SubSystem"].ToString().Length > 0 ? "/" + ConfigurationSettings.AppSettings["SubSystem"].ToString() : "");

			if (!IsPostBack)
			{
				PanelHeader.BackImageUrl = "~/App_UI/Images/PageView/" +
				                           ConfigurationSettings.AppSettings["Header"].ToString();
				HttpCookie cookie = Request.Cookies["UserDetail"];

			    string sessionEmpSeq = Convert.ToString(Session["EmpSeq"]);
                string cookieEmpSeq = Convert.ToString(cookie != null ? cookie["EmpSeq"] : "");

                if (cookie != null &&(string.IsNullOrEmpty(sessionEmpSeq) || sessionEmpSeq != cookieEmpSeq ))
				{
					Session["EmpSeq"] = cookie["EmpSeq"];
					Session["UserName"] = cookie["UserName"];
					Session["UserSeq"] = cookie["UserSeq"];
					ssMng.SetLoginSession((string)Session["UserSeq"],
						(string)Session["EmpSeq"],
						(string)Session["UserName"],
                        cookie["WorkingJobSiteSeq"] );
				}

				if (Session["UserSeq"] == null)
				{
					Response.Redirect("~/App_UI/Forms/Login.aspx");
				}
				else
				{
					GetUserInfo(ssMng.UserSeq);
					CreatedMenu(ssMng.UserSeq);
				}
			}
            else
			{
                //HttpCookie cookie = Request.Cookies["UserDetail"];
                //if (cookie != null)
                //{
                //    Session["EmpSeq"] = cookie["EmpSeq"];
                //    Session["UserName"] = cookie["UserName"];
                //    Session["UserSeq"] = cookie["UserSeq"];
                //    new SsMng().SetLoginSession((string)Session["UserSeq"],
                //        (string)Session["EmpSeq"],
                //        (string)Session["UserName"],
                //        cookie["WorkingJobSiteSeq"],
                //        cookie["Height"]);

                //}

				if (Session["UserSeq"] == null && !Page.IsCallback)
				{
					Response.Redirect("~/App_UI/Forms/Login.aspx");
				}
			}

	        if (Session["EmpSeq"] != null)
            {
                //cmdInbox.OnClientClick = "openTaskLists('@ServerName', '@Seq')"
                //    .Replace("@ServerName", strServerName).Replace("@Seq", ssMng.EmpSeq);
                lbNotification.OnClientClick = "openTaskLists('@ServerName', '@Seq')"
                    .Replace("@ServerName", strServerName).Replace("@Seq", ssMng.EmpSeq);
                UpdateUnreadCount();
            }

            SetPageTitle("ระบบบริหารทรัพยากรบุคคล");
        }

        private void SetPageTitle(string moduleTitle)
        {
            if (!String.IsNullOrEmpty(Page.Title)) return;
            string pageFileName = Path.GetFileName(Request.Path);
            string pageTitle = bll.GetTitlePage(pageFileName);
            pageTitle = String.IsNullOrEmpty(pageTitle) ? moduleTitle :
                String.Format("{0} - {1}", moduleTitle, pageTitle);
            Page.Title = pageTitle;
        }

        //protected string GetSystemName()
        //{
        //    IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        //    try
        //    {
        //        string strResult = "";
        //        string sql = "select system_name"
        //            + " from sys_system_controls";
        //        DataTable dt = new DataTable();
        //        dbManager.Open();
        //        dt = dbManager.ExecuteDataSet(CommandType.Text, sql).Tables[0];

        //        if (dt.Rows.Count > 0)
        //        {
        //            strResult = dt.Rows[0][0].ToString();
        //        }

        //        return strResult;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    finally
        //    {
        //        dbManager.Dispose();
        //    }
        //}
        public void GetUserInfo(string UserSequence)
        {
            lblUserName.Text = "";

            DataSet ds = userBLL.LoadUser(Int32.Parse(UserSequence), (int?)null, (int?)null, "");
            DataTable dt = null;
            if (ds != null)
            {
                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    lblUserName.Text = dt.Rows[0]["USER_NAME"].ToString();

            }
        }
        public void CreatedMenu(string strUserSeq)
        {
            //HttpCookie cookie = new HttpCookie("UserDetail"); 
            IList<SysMenuItemListInfo> dataOfUser = bll.LoadMenuByUsername(Convert.ToInt32(strUserSeq) );
            RadMenu1.DataSource = dataOfUser;
            RadMenu1.DataBind();
            //SetColorMenuNonAccessible(dataOfUser, false); // param2: true ถ้าต้องการให้แสดงเมนูที่ไม่มีสิทธิ์
        }

        private void SetColorMenuNonAccessible(IList<SysMenuItemListInfo> dataOfUser, bool showAsRedOrHide)
        {
            foreach (var o in dataOfUser)
            {
                try
                {
                    if (!o.UserCanAccess)
                    {
                        if (showAsRedOrHide && RadMenu1.FindItemByValue(Convert.ToString(o.Seq)) != null)
                            RadMenu1.FindItemByValue(Convert.ToString(o.Seq)).ForeColor = Color.Red;
                        else if (RadMenu1.FindItemByValue(Convert.ToString(o.Seq)) != null)
                            RadMenu1.FindItemByValue(Convert.ToString(o.Seq)).Visible = false;
                    }
                }
                catch
                {
                }
            }
        }
        protected void UpdateUnreadCount()
        {
            int nUnreadCount = 0;
            try { nUnreadCount = (send ?? new B_MessageSend()).GetUnreadCount(ssMng.EmpSeq); }
            catch { }

            int nOldUnreadCount = 0;
            try { nOldUnreadCount = Convert.ToInt32(Session["UnreadCount"]); }
            catch { }

            if (nUnreadCount > nOldUnreadCount)
            {
                ShowNotification(nUnreadCount);
            }

            Session["UnreadCount"] = nUnreadCount;
            //cmdInbox.Text = string.Format("ข้อความใหม่ {0}", nUnreadCount);
        }
        protected void ShowNotification(int nUnreadCount)
        {
            lbNotification.Text = "คุณมีข้อความที่ยังไม่ได้อ่าน " + nUnreadCount.ToString();
            RadToolTip1.Show();
        }
        protected void cmdSignOut_Click(object sender, ImageClickEventArgs e)
        {
            HttpCookie cookie = Request.Cookies["UserDetail"];

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }

            RadMenu1.Items.Clear();
            Session.Abandon();
            Response.Redirect("//" + strServerName + "/" + ConfigurationSettings.AppSettings["SubSystemPrefix"] + "ESS/APP_UI/Forms/Login.aspx");
        }

        protected void cmdLogout_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["UserDetail"];

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }

            Session.Abandon();
            Response.Redirect(@"~\App_UI\Forms\Login.aspx");
        }

        protected void cmdInbox_Click(object sender, EventArgs e)
        {
        }

        protected void cmdBackToSelectSystem_Click(object sender, EventArgs e)
        {
            Response.Redirect("//" + strServerName + "/ESS/App_UI/Forms/SelectSystem.aspx");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var Test = 1;
        }

        //protected void Page_Load(object sender, EventArgs e)
        //{
        //    if (!IsPostBack)
        //    {
        //        HttpCookie cookie = Request.Cookies["UserDetail"];
        //        if (cookie != null)
        //        {
        //            Session["EmpSeq"] = cookie["EmpSeq"];
        //            Session["UserName"] = cookie["UserName"];
        //            Session["UserSeq"] = cookie["UserSeq"];
        //        }
        //        else
        //        {
        //            //Session["EmpSeq"] = "1";
        //            //Session["UserSeq"] = "2";
        //        }

        //        GetUserInfo(ssMng.UserSeq);
        //        CreatedMenu(ssMng.UserSeq);

        //        switch (GetSystemName())
        //        {
        //            case "DEP":
        //            default:
        //                PanelHeader.BackImageUrl = "~/App_UI/Images/PageView/Header.jpg";
        //                break;
        //            case "ITPF":
        //                PanelHeader.BackImageUrl = "~/App_UI/Images/PageView/Header_ITPF.jpg";
        //                break;
        //        }
        //    }

        //    UpdateUnreadCount();
        //}
        //protected string GetSystemName()
        //{
        //    IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        //    try
        //    {
        //        string strResult = "";
        //        string sql = "select system_name"
        //            + " from sys_system_controls";
        //        DataTable dt = new DataTable();
        //        dbManager.Open();
        //        dt = dbManager.ExecuteDataSet(CommandType.Text, sql).Tables[0];

        //        if (dt.Rows.Count > 0)
        //        {
        //            strResult = dt.Rows[0][0].ToString();
        //        }

        //        return strResult;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    finally
        //    {
        //        dbManager.Dispose();
        //    }
        //}
        //public void GetUserInfo(string UserSequence)
        //{
        //    lblUserName.Text = "";

        //    DataSet ds = userBLL.LoadUser(Int32.Parse(UserSequence), (int?)null, (int?)null, "");
        //    DataTable dt = null;
        //    if (ds != null)
        //    {
        //        dt = ds.Tables[0];
        //        if (dt.Rows.Count > 0)
        //            lblUserName.Text = dt.Rows[0]["USER_NAME"].ToString();

        //    }
        //}
        //public void CreatedMenu(string strUserSeq)
        //{
        //    //HttpCookie cookie = new HttpCookie("UserDetail");
        //    RadMenu1.DataSource = bll.LoadMenuByUsername(Convert.ToInt32(strUserSeq));
        //    RadMenu1.DataBind();
        //}
        //protected void UpdateUnreadCount()
        //{
        //    int nUnreadCount = send.GetUnreadCount(ssMng.EmpSeq);
        //    int nOldUnreadCount = Convert.ToInt32(Session["UnreadCount"]);

        //    if (nUnreadCount > nOldUnreadCount)
        //    {
        //        ShowNotification(nUnreadCount);
        //    }

        //    Session["UnreadCount"] = nUnreadCount;
        //    lblInboxCount.Text = nUnreadCount.ToString();
        //}
        //protected void ShowNotification(int nUnreadCount)
        //{
        //    lbNotification.Text = "คุณมีข้อความที่ยังไม่ได้อ่าน " + nUnreadCount.ToString();
        //    RadToolTip1.Show();
        //}
        //protected void cmdSignOut_Click(object sender, ImageClickEventArgs e)
        //{
        //    Session.Abandon();
        //    string strURL = @"//" + strServerURL + @"/" + "DEP-GERP" + @"/App_UI/Forms/Default.aspx";

        //    Response.Redirect(strURL);
        //    //Response.Redirect(@"~\App_UI\Forms\Login.aspx");
        //}

        //protected void cmdLogout_Click(object sender, EventArgs e)
        //{
        //    HttpCookie cookie = Request.Cookies["UserDetail"];

        //    if (cookie != null)
        //    {
        //        cookie.Expires = DateTime.Now.AddDays(-1);
        //    }

        //    Session.Abandon();
        //    Response.Redirect(@"~\App_UI\Forms\Login.aspx");
        //}

        //protected void cmdInbox_Click(object sender, EventArgs e)
        //{
        //    string strURL = @"//" + strEssURL + @"/" + "DEP-GERP" + @"/App_UI/Forms/TaskLists.aspx";

        //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Redirect", "window.open('" + strURL + "','_blank')", true);
        //    //Response. .Redirect(@"~\App_UI\Forms\TaskLists.aspx");
        //}

    }
}
